package cn.elves.model.auth.config.interceptor;

import cn.elves.model.auth.service.AuthenticationService;
import lombok.Data;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashSet;


public class AuthInterceptor implements HandlerInterceptor {

    private AuthenticationService authenticationService;

    public AuthInterceptor(AuthenticationService authenticationService) {
        this.authenticationService = authenticationService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(request.getHeader("userId") == null){
            response.setStatus(401);
            return false;
        }


        if(requestInWriteList(new RequestParamWrapper(request.getRequestURI(), request.getMethod()))){
            return true;
        }
        Long userId = Long.parseLong(request.getHeader("userId"));
        Boolean isAvailable = authenticationService.decideInterfaceAvailable(userId, request.getRequestURI(), request.getMethod());
        if(!isAvailable){
            response.setStatus(403);
            return false;
        }
        return true;
    }

    private boolean requestInWriteList(RequestParamWrapper requestParamWrapper) {
        HashSet<RequestParamWrapper> writeList = getWriteList();
        return writeList.contains(requestParamWrapper);

    }

    private HashSet<RequestParamWrapper> getWriteList() {
        HashSet<RequestParamWrapper> requestParamWrappers = new HashSet<>();
        RequestParamWrapper requestParamWrapper = new RequestParamWrapper("/auth/availableMenu","GET");
        RequestParamWrapper requestParamWrapper1 = new RequestParamWrapper("/error","GET");
        requestParamWrappers.add(requestParamWrapper);
        requestParamWrappers.add(requestParamWrapper1);
        return requestParamWrappers;
    }

    @Data
    class RequestParamWrapper{

        private String url;

        private String method;

        public RequestParamWrapper(String url, String method) {
            this.url = url;
            this.method = method;
        }
    }
}
